package com.example.gaodemap;

import android.Manifest;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;

import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity implements LocationSource, AMapLocationListener {

    private MapView mMapView = null;
    //定义AMap 地图对象的操作方法与接口
    private AMap aMap = null;

    /*
    定位需要的声明
     */
    //定位服务类。此类提供单次定位、持续定位、最后位置相关功能
    private AMapLocationClient mLocationClient = null;
    //定位参数
    private AMapLocationClientOption mLocationOption = null;
    //定位监听器
    private OnLocationChangedListener mLocationListener = null;

    //标识，用于判断是否只显示一次定位信息和用户重新定位
    private boolean isFristLoc = true;

    private static final int REQUEST_LOCATION = 1234;
    private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
    private static final String COARSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;

   @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //获取地图控件的引用
        mMapView = findViewById(R.id.map);
        //在activity执行onCreate时执行mMapView.onCreate(saveIndtanceState),创建地图
        mMapView.onCreate(savedInstanceState);
        //获取地图
        if (aMap == null){
            aMap = mMapView.getMap();
        }

        /*
        1.设置显示的按钮，并且可以点击
        2.设置定位监听
         */
        aMap.getUiSettings().setMyLocationButtonEnabled(true);
        aMap.setLocationSource(this);
        aMap.setMyLocationEnabled(true);
//        aMap.setOnMapClickListener(this);
        /*
        初始化定位蓝点样式
         */
       MyLocationStyle myLocationStyle = new MyLocationStyle();
       myLocationStyle.interval(2000);
       myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);
//       myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.mipmap.location));
       aMap.setMyLocationStyle(myLocationStyle);
       aMap.setMyLocationEnabled(true);

       getLocationPermissiion();
    }

    private void getLocationPermissiion() {
        String[] permission = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION,};
        //explicitly check access fine location and access course location检查权限
        if (ContextCompat.checkSelfPermission(this.getApplicationContext(), FINE_LOCATION) ==
                PackageManager.PERMISSION_GRANTED) {
            if (ContextCompat.checkSelfPermission(this.getApplicationContext(), COARSE_LOCATION) ==
                    PackageManager.PERMISSION_GRANTED) {
                initLocation();
            } else {
                //request permissions申请权限
                ActivityCompat.requestPermissions(this, permission, REQUEST_LOCATION);
            }
        } else {
            //request permissions
            ActivityCompat.requestPermissions(this, permission, REQUEST_LOCATION);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case REQUEST_LOCATION:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    initLocation();
                }
                break;
        }
    }

    private void initLocation() {
       mLocationClient = new AMapLocationClient(getApplicationContext());
       mLocationClient.setLocationListener(this);
       mLocationOption = new AMapLocationClientOption();
       mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
       mLocationOption.setNeedAddress(true);
       mLocationClient.setLocationOption(mLocationOption);
       mLocationOption.setLocationCacheEnable(false);
       mLocationOption.setInterval(2000);
       mLocationClient.startLocation();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestory时执行mMapView.onDestory(),销毁地图
        mMapView.onDestroy();
        if (mLocationClient != null){
            mLocationClient.onDestroy();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }

    //激活定位
    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
       mLocationListener = onLocationChangedListener;
    }

    @Override
    public void deactivate() {
        mLocationListener = null;
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
        }
        mLocationClient = null;
    }

    //定位回调函数,AmapLocation定位信息类，定位完成后的位置信息
    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {

       if (aMapLocation != null){
           if (aMapLocation.getErrorCode() == 0){
               /*
               定位成功回调信息，设置相关信息
                */
               aMapLocation.getLocationType();//获取当前定位结果来源
               aMapLocation.getLatitude();//获取纬度
               aMapLocation.getLongitude();//获取经度
               aMapLocation.getAccuracy();//获取京都信息
               aMapLocation.getAddress();
               aMapLocation.getCountry();
               aMapLocation.getProvince();
               aMapLocation.getCity();
               aMapLocation.getDistrict();
               aMapLocation.getStreet();
               aMapLocation.getStreetNum();
               aMapLocation.getCityCode();
               aMapLocation.getAdCode();//地图编号
               /*
               获取定位时间
                */
               SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
               Date date = new Date(aMapLocation.getTime());
               dateFormat.format(date);

               /*
               如果不设置标志位，此时在推动地图时，它会不断将地图移动到当前的位置上
                */
               if (isFristLoc){
                   aMap.moveCamera(CameraUpdateFactory.zoomTo(17));//设置缩放比例
                   aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude())));
                   aMap.addMarker(getMarkerOption(aMapLocation));
                   /*
                   点击定位按钮能够将地图中心移动到定位点
                    */
                   mLocationListener.onLocationChanged(aMapLocation);
                   isFristLoc = false;
               }
           }else {
               Log.e("AmapError", "location Error, ErrCode:"
                       + aMapLocation.getErrorCode() + ", errInfo:"
                       + aMapLocation.getErrorInfo());
               Toast.makeText(getApplicationContext(), "定位失败", Toast.LENGTH_SHORT).show();
           }
       }
    }

    private MarkerOptions getMarkerOption(AMapLocation aMapLocation) {
       MarkerOptions markerOptions = new MarkerOptions();
       markerOptions.position(new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude()));
//       markerOptions.icon(BitmapDescriptorFactory.fromResource(R.mipmap.location));
       StringBuffer buffer = new StringBuffer();
       buffer.append(aMapLocation.getProvince() + "" + aMapLocation.getCity() + "" +
               aMapLocation.getStreet() + "" + aMapLocation.getStreetNum() + "附近");
       markerOptions.title(buffer.toString());
       markerOptions.period(60);

       return markerOptions;
    }
}
